package com.southwind.springboottest.study.Java中通讯.udp协议;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpServerExample {

    public static void main(String[] args) throws Exception {
        // 创建一个 UDP 套接字，监听 9876 端口
        DatagramSocket socket = new DatagramSocket(9876);
        byte[] receiveData = new byte[1024]; // 缓冲区，用于接收数据

        while (true) {
            // 创建数据包，用于接收数据
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

            // 接收数据包
            socket.receive(receivePacket);

            // 解析数据包内容
            String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("Received: " + message);

            // 获取客户端地址和端口
            InetAddress clientAddress = receivePacket.getAddress();
            int clientPort = receivePacket.getPort();

            // 准备响应数据包
            String response = "Hello, UDP!";
            DatagramPacket sendPacket = new DatagramPacket(response.getBytes(), response.getBytes().length, clientAddress, clientPort);

            // 发送响应数据包
            socket.send(sendPacket);
        }
    }
}

